package com.depthsdata.coe.api;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.depthsdata.coe.dao.BusinessNodeDAOQueryBean;
import com.depthsdata.coe.dao.BusinessUnitDAOQueryBean;
import com.depthsdata.coe.service.BusinessNodeBean;
import com.depthsdata.coe.service.BusinessUnitBean;
import com.depthsdata.coe.service.IBusinessNodeService;
import com.ourteam.frame.controller.AbstractCRUDServiceController;
import com.ourteam.frame.web.OperationResult;

@Controller
@CrossOrigin
@RequestMapping("/api/COE/businessNode")
public class BusinessNodeManageAPI
		extends AbstractCRUDServiceController<BusinessNodeDAOQueryBean, BusinessNodeSearchBean, BusinessNodeBean> {

	@Autowired
	private IBusinessNodeService businessNodeService;

	@Override
	protected BusinessNodeDAOQueryBean newQueryBean() {
		return new BusinessNodeDAOQueryBean();
	}

	@Override
	protected int queryCount(BusinessNodeDAOQueryBean queryBean) throws Exception {
		return businessNodeService.queryBusinessNodeCount(queryBean);
	}

	@Override
	protected BusinessNodeBean[] queryData(BusinessNodeDAOQueryBean queryBean) throws Exception {
		return businessNodeService.queryBusinessNodes(queryBean);
	}

	@Override
	protected void deleteData(long[] ids) throws Exception {

		businessNodeService.deleteBusinessNodes(ids);

	}

	@Override
	protected BusinessNodeBean getDataById(long id) throws Exception {
		return businessNodeService.getBusinessNodeById(id);
	}

	@Override
	protected void saveData(BusinessNodeBean dataBean) throws Exception {

		BusinessNodeDAOQueryBean queryBean = new BusinessNodeDAOQueryBean();

		queryBean.createCriteria().andProcessDiagramNodeIdEqualTo(dataBean.getProcessDiagramNodeId());

		BusinessNodeBean[] nodeBeans = businessNodeService.queryBusinessNodes(queryBean);

		if (nodeBeans.length == 0) {
			businessNodeService.addNewBusinessNode(dataBean);
		} else {
			dataBean.setId(nodeBeans[0].getId());
			businessNodeService.modifyBusinessNode(dataBean);
		}

	}

	@RequestMapping("/removeByDiagramNodeId")
	@ResponseBody
	public OperationResult removeByDiagramNodeId(final @RequestParam(required = true) String diagramNodeId)
			throws Exception {

		BusinessNodeDAOQueryBean queryBean = new BusinessNodeDAOQueryBean();

		queryBean.createCriteria().andProcessDiagramNodeIdEqualTo(diagramNodeId);

		BusinessNodeBean[] nodeBeans = businessNodeService.queryBusinessNodes(queryBean);

		if (nodeBeans.length > 0) {
			businessNodeService.deleteBusinessNodes(new long[] { nodeBeans[0].getId() });
		}

		return OperationResult.SUCCESS_RESULT;

	}

}
